﻿//-------------
// <copyright file="AccountController.cs" company="Uncas">
//     Copyright (c) Ole Lynge Sørensen. All rights reserved.
// </copyright>
//-------------

namespace Uncas.Katas.SimpleMembership.Web.Controllers
{
    using System.Web.Mvc;
    using Uncas.Katas.SimpleMembership.Domain;

    /// <summary>
    /// Handles account specific actions.
    /// </summary>
    public class AccountController : Controller
    {
        /// <summary>
        /// The account service.
        /// </summary>
        private IAccountService accountService;

        /// <summary>
        /// The user repository.
        /// </summary>
        private IUserRepository userRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountController"/> class.
        /// </summary>
        /// <param name="accountService">The account service.</param>
        /// <param name="userRepository">The user repository.</param>
        public AccountController(
            IAccountService accountService,
            IUserRepository userRepository)
        {
            this.accountService = accountService;
            this.userRepository = userRepository;
        }

        /// <summary>
        /// Prepares the view where the user can log on.
        /// </summary>
        /// <returns>The view where the user can log on.</returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        /// Logs the user on.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <returns>Redirect to the front page.</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(
            string userName,
            string password)
        {
            bool credentialsAreValid = 
                this.userRepository.ValidateCredentials(
                userName, 
                password);
            if (credentialsAreValid)
            {
                this.accountService.LogOn(userName);
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        /// <summary>
        /// Logs the user off.
        /// </summary>
        /// <returns>Redirect to the front page.</returns>
        public ActionResult LogOff()
        {
            this.accountService.LogOff();
            return RedirectToAction("Index", "Home");
        }
    }
}
